package com.booter.ws.controller;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author lcw
 * @date 2023/8/16 18:35
 */
@RestController
@RequestMapping("test")
public class DownLoadController {

    @RequestMapping("download")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try (InputStream in = new FileInputStream("/Users/lichunwen/Documents/流程规则梳理.xlsx");
             OutputStream os = response.getOutputStream();
             BufferedOutputStream buffer = new BufferedOutputStream(os);
             XSSFWorkbook book = new XSSFWorkbook(in)) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + System.currentTimeMillis() + ".xlsx");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setCharacterEncoding("UTF-8");
            book.write(buffer);
            buffer.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public void upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        OutputStream os = response.getOutputStream();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=x_" + System.currentTimeMillis() + ".xlsx");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setCharacterEncoding("UTF-8");
        os.write(file.getBytes());
        os.close();
    }
}
